package com.happyass.service.excel.impl;

import com.happyass.dao.UserDao;
import com.happyass.pojo.User;

import com.happyass.service.excel.UserExcelService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Service
public class UserExcelServiceImpl implements UserExcelService {
    @Autowired(required = false)
    UserDao userDao;
    @Override
    public void excel(HttpServletResponse response) throws IOException {
        //定义要导出的数据
        List<User> list = userDao.findAll();
        //操作office文件对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个excel对象
        HSSFSheet sheet = workbook.createSheet("VIP用户信息");
        //创建一行作为表头
        HSSFRow colName=sheet.createRow(0);
        //定义表头信息
        String[] title ={"编号","姓名","用户名","身份证号码","生日","地址","电话","状态"};
        //在excel中写入表头
        for(int i=0;i<title.length;i++){
            colName.createCell(i).setCellValue(title[i]);
        }
        //写入要导出的数据
        for (int i = 0; i <list.size() ; i++) {
            //创建写入行
            HSSFRow row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(list.get(i).getUserId());

            row.createCell(1).setCellValue(list.get(i).getUserLocalName());
            row.createCell(2).setCellValue(list.get(i).getUserName());
            row.createCell(3).setCellValue(list.get(i).getUserIdenty());
            row.createCell(4).setCellValue(list.get(i).getUserBirth());
            row.createCell(5).setCellValue(list.get(i).getUserAddr());
            row.createCell(6).setCellValue(list.get(i).getUserTel());
            if (list.get(i).getUserStatus()==1){
                row.createCell(7).setCellValue("启用");
            }else{
            row.createCell(7).setCellValue("禁用");
        }
        try{
            String fileName="用户列表";

            fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
            //设置响应方式
            response.reset();
            //设置响应文件的名字
            response.setHeader("Content-disposition","attachment; filename="+fileName+".xls");
            response.setContentType("application/msexcel");
            //写入你要下载文件
            workbook.write(response.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
            }
        }
    }
}

